package com.owen.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class MilkFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();

        HttpSession session = ((HttpServletRequest) servletRequest).getSession();

        if (uri.contains("static") || uri.equalsIgnoreCase("/goLoginInOne") ||
                uri.equalsIgnoreCase("/goLoginIn") || uri.equalsIgnoreCase("/toZhuce") ||
                uri.equalsIgnoreCase("/login/userLogin") || uri.equalsIgnoreCase("/user/zhuce")
        ) {
            filterChain.doFilter(req, servletResponse);
        } else if (session.getAttribute("login") != null) {
            filterChain.doFilter(req, servletResponse);
        } else if (session.getAttribute("login") == null) {
            System.err.println(uri + "-11-> 该请求已被拦截");

            resp.setHeader("Cache-Control","no-cache");
            resp.sendRedirect("/goLoginInOne");

        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

}
